#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

myFILE* my_fopen(const char* path, const char* mode)
{
    int fd = 0;
    int flag = 0;
    if(strcmp(mode,"r") == 0)
    {
        flag |= (O_RDONLY);
    }
    else if(strcmp(mode,"w") == 0)
    {
        flag |=(O_WRONLY | O_CREAT | O_TRUNC);
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag |=(O_WRONLY | O_CREAT | O_APPEND);
    }
    else 
    {
        //do nothing
    }

    if(flag & O_CREAT)//认为文件不存在
    {
        fd = open(path,flag,0666);
    }
    else //认为文件存在
    {
        fd = open(path,flag);
    }

    if(fd < 0)
    {//文件打开失败
        errno = 2;
        return NULL;
    }   
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(fp == NULL)
    {
        errno = 3;
        return NULL;
    }
    fp->fileno = fd;
    fp->end = 0;
    fp->flag = FLUSH_LINE;
    return fp;
}
int my_fwrite(const char* s, int num, myFILE* stream)          
{
    //是写入到缓冲区中
    memcpy(stream->buffer + stream->end,s,num);
    stream->end += strlen(s);
    
    //判断是否需要刷新
    if((stream->flag & FLUSH_LINE) && stream->end > 0 && stream->buffer[stream->end - 1] == '\n')
    {
        my_fflush(stream);
    }
    return stream->end;
}
int my_fflush(myFILE* stream)                       
{
    if(stream->end > 0)
    {
        write(stream->fileno,stream->buffer,stream->end);//刷新到操作系统
        fsync(stream->fileno);//内核数据缓冲区刷新到内核中
        stream->end = 0;
    }
    return 0;
}
int my_fclose(myFILE* stream)                       
{
    my_fflush(stream);
    int ret =  close(stream->fileno);
    free(stream);
    return ret;
}
